import { Component, spring } from 'j-spring';
import { Socket as cSocket, io } from 'socket.io-client';
import { Controller, Get, springWebModule } from 'j-spring-web';
import { socketModule, SocketHandler, Server, Socket } from '../src/index';

@Controller('testApi')
class TestApi {
  @Get()
  getMsg() {
    return { msg: 'hello world!' };
  }
}

const config = {
  'j-spring': {
    log: 'error',
  },
  'socket-io': {
    path: '/test-socket/',
  },
};

export interface ServerEvent {
  login(id: string, name: string): void;
  recive_user_msg(msg: string, cb: (n: number) => string): void;
}

export interface ClientEvent {
  recive_server_msg(msg: string): void;
}

export interface IoEvent {
  ping: () => void;
}

export type User = {
  id: string; //用户id
  name: string;
};

export type IoType = Server<ServerEvent, ClientEvent, IoEvent, User>;

export type SocketType = Socket<ServerEvent, ClientEvent, IoEvent, User>;

@Component()
class DiyHandler implements SocketHandler<SocketType, IoType> {
  getHandlerName(): string {
    return 'name:DiyHandler';
  }
  async registerEvent(socket: SocketType, io: IoType): Promise<void> {
    socket.on('login', (id, name) => {
      socket.data = { id, name };
      console.log(`用户登陆:${JSON.stringify(socket.data)}`);

      socket.emit('recive_server_msg', '你连接上服务器了，发送业务请求吧');
    });

    socket.on('recive_user_msg', (msg, d) => {
      console.log(`recive_user_msg => ${msg}`);
      d(100);
    });
  }
  isSocketHandler(): boolean {
    return true;
  }
  isAutoRegister(): boolean {
    return true;
  }
}

spring
  .loadConfig(config)
  .bindModule([springWebModule([TestApi]), socketModule([DiyHandler])])
  .invokeStarter()
  .then(() => {
    setTimeout(mainTest, 2000);
  });

const mainTest = async () => {
  console.log('开始测试!');

  // 设置服务器地址
  const socket: cSocket<ClientEvent, ServerEvent> = io('ws://127.0.0.1:3000', {
    path: '/test-socket/',
  }); // 假设你的Socket.IO服务器运行在 http://localhost:3000

  // 监听连接事件
  socket.on('connect', () => {
    console.log('Connected to the server!');

    // 可以在这里发送消息给服务器
    socket.emit('login', '1', 'xiaoming');
  });

  // 监听来自服务器的消息
  socket.on('recive_server_msg', (data: string) => {
    console.log('Received message from server:', data);
    socket.emit('recive_user_msg', '大数据请求', (d) => {
      console.log(`接受参数:${d}`);
      return d + '_client';
    });
  });

  // 监听断开连接事件
  socket.on('disconnect', () => {
    console.log('Disconnected from the server!');
  });

  socket.on('connect_error', (e) => {
    console.log(e);
  });
};
